"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : 系统内部使用工具
Case Name   : pscp -h指定正确主机名列表文件与正确源文件及正确目标目录
Create At   : 2022/4/24
Owner       : opentestcase023
Description :
    1.创建主机名文件及传输源文件
    2.pscp -h指定正确主机名列表文件与正确源文件及正确目标目录
    3.清理环境
Expect      :
    1.创建成功
    2.执行成功，返回相应结果
    3.清理成功
History     :
"""
import os
import unittest

from yat.test import Node
from yat.test import macro

from testcase.utils.Common import Common
from testcase.utils.Common import CommonSH
from testcase.utils.Logger import Logger

primary_sh = CommonSH('PrimaryDbUser')


@unittest.skipIf(3 > primary_sh.get_node_num(), '非1+2不执行')
class Tools(unittest.TestCase):
    def setUp(self):
        self.log = Logger()
        self.log.info(f'-----{os.path.basename(__file__)} start-----')
        self.primary_root_node = Node('PrimaryRoot')
        self.primary_node = Node('PrimaryDbUser')
        self.s_root_node1 = Node('Standby1Root')
        self.s_root_node2 = Node('Standby2Root')
        self.com_root = CommonSH("PrimaryRoot")
        self.dir_path = os.path.dirname(macro.DB_INSTANCE_PATH)
        self.ssh_lis_file = os.path.join(f'{self.dir_path}', 'ssh_lis_file')
        self.ssh_file = os.path.join('~', '.ssh', '*')
        self.common = Common()

    def test_pscp(self):
        text = '-----step1:创建主机名列表文件;expect:成功-----'
        test = '-----查看主机名-----'
        self.log.info(test)
        s1_node_name = self.common.get_sh_result(self.s_root_node1, "uname -n")
        self.assertIsNotNone(s1_node_name, '执行失败:' + text)
        s2_node_name = self.common.get_sh_result(self.s_root_node2, "uname -n")
        self.assertIsNotNone(s2_node_name, '执行失败:' + text)
        add_cmd = f'touch {self.ssh_lis_file};' \
                  f'chmod -R 755 {self.ssh_lis_file};' \
                  f"echo -e '{s1_node_name}\n{s2_node_name}' " \
                  f"> {self.ssh_lis_file};" \
                  f"cat {self.ssh_lis_file}"
        self.log.info(add_cmd)
        add_res = self.common.get_sh_result(self.primary_root_node, add_cmd)
        for name in [s1_node_name, s2_node_name]:
            self.assertIn(name, add_res, '主机列表文件创建失败')

        self.log.info('-----创建传输源文件-----')
        global file_path
        file_path = os.path.join(f'{self.dir_path}', 'backup.txt')
        add_cmd = f'touch {file_path};ls {self.dir_path}'
        self.log.info(add_cmd)
        add_res = self.common.get_sh_result(self.primary_root_node, add_cmd)
        self.assertIn('backup.txt', add_res, '文件构建失败')

        text = '-----step2:pscp -h指定正确主机名列表文件与正确源文件及正确目标目录;expect:成功-----'
        self.log.info(text)
        self.log.info("-----创建root互信-----")
        result = self.common.get_sh_result(self.primary_root_node,
                                           f"ls {macro.DB_SCRIPT_PATH}")
        if "gs_sshexkey" not in result:
            cmd = f"cd {macro.DB_SCRIPT_PATH}/../; " \
                  f"tar -zxvf openGauss-Package-bak*.tar.gz > /dev/null"
            result = self.common.get_sh_result(self.primary_root_node, cmd)
            self.log.info(result)
            result = self.common.get_sh_result(self.primary_root_node,
                                               f"ls {macro.DB_SCRIPT_PATH}")
            self.log.info(result)
            if "gs_sshexkey" not in result:
                raise Exception("cat not find gs_sshexkey, Please check!")
        self.host_tuple = (self.primary_root_node.ssh_host,
                           self.s_root_node1.ssh_host,
                           self.s_root_node2.ssh_host)
        self.params = {'-f': 'test_hosts'}
        self.com_root.exec_gs_sshexkey(macro.DB_SCRIPT_PATH,
                                       *self.host_tuple,
                                       **self.params)

        self.log.info('-----执行pscp命令-----')
        pscp_cmd = f"pscp -h {self.ssh_lis_file} {file_path} {self.dir_path}"
        self.log.info(pscp_cmd)
        pscp_res = self.common.get_sh_result(self.primary_root_node, pscp_cmd)
        self.assertIn('SUCCESS', pscp_res, '执行失败' + text)
        check_cmd = f'ls {self.dir_path}'
        self.log.info(check_cmd)
        s1_res = self.common.get_sh_result(self.s_root_node1, check_cmd)
        s2_res = self.common.get_sh_result(self.s_root_node2, check_cmd)
        self.assertIn('backup.txt', s1_res, '文件传输失败')
        self.assertIn('backup.txt', s2_res, '文件传输失败')

    def tearDown(self):
        text = '-----step3:清理环境，删除主机列表文件及传输;expect:成功-----'
        self.log.info(text)
        fil_del_cmd = f'rm -rf {file_path}'
        self.log.info(fil_del_cmd)
        rm_res = self.common.get_sh_result(self.primary_root_node,
                                           f'rm -rf {self.ssh_lis_file}')
        p_rm_res = self.common.get_sh_result(self.primary_root_node,
                                             fil_del_cmd)
        s1_rm_res = self.common.get_sh_result(self.s_root_node1, fil_del_cmd)
        s2_rm_res = self.common.get_sh_result(self.s_root_node2, fil_del_cmd)
        self.log.info('-----删除root互信-----')
        del_cmd = f'rm -rf {self.ssh_file}'
        self.log.info(del_cmd)
        del_res1 = self.common.get_sh_result(self.primary_root_node, del_cmd)
        del_res2 = self.common.get_sh_result(self.s_root_node1, del_cmd)
        del_res3 = self.common.get_sh_result(self.s_root_node2, del_cmd)
        self.assertEqual('', rm_res, '文件删除失败')
        self.assertEqual('', p_rm_res, '文件删除失败')
        self.assertEqual('', s1_rm_res, '文件删除失败')
        self.assertEqual('', s2_rm_res, '文件删除失败')
        self.assertEqual('', del_res1, '互信删除失败')
        self.assertEqual('', del_res2, '互信删除失败')
        self.assertEqual('', del_res3, '互信删除失败')
        self.log.info(f'-----{os.path.basename(__file__)} end-----')
